<!-- 文件: front_demo/demo/src/views/UserManagement.vue -->
<template>
  <div class="user-management" style="width: 100%; padding: 10px">
<!--    <h2>用户管理</h2>-->

    <!-- 搜索栏 -->
    <div style="margin: 10px 0; display: flex; align-items: center;">
      <el-input
          v-model="searchUsername"
          placeholder="请输入用户名搜查询"
          style="width: 200px; margin-right: 10px"
          clearable
          @keyup.enter="searchUsers"
      />
      <el-button type="primary" @click="searchUsers">查询</el-button>
      <el-button type="success" @click="resetSearch" style="margin-right: 10px">重置</el-button>

      <!-- 添加用户按钮 -->
      <el-button
          type="warning"
          @click="showAddUserDialog"
          v-if="currentUser.role === 'ADMIN'">
        添加用户
      </el-button>
    </div>

    <!-- 用户列表 -->
    <el-table :data="users" border stripe style="width: 100%">
      <!-- 数据库ID列 - 普通用户显示占位符，管理员显示真实值 -->
      <el-table-column prop="id" label="数据库ID" width="100">
        <template #default="scope">
          <span>{{ currentUser.role === 'ADMIN' ? scope.row.id : '********' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"/>

      <!-- 密码列（所有用户都可见，但只有管理员能查看真实密码） -->
      <el-table-column label="密码">
        <template #default="scope">
          <div style="display: flex; align-items: center;">
            <!-- 所有用户都显示密码占位符或真实密码（仅管理员可见） -->
            <span>{{
                (currentUser.role === 'ADMIN' && passwordVisible[scope.row.id]) ? scope.row.password : '********'
              }}</span>
            <!-- 只有管理员能看到并点击眼睛图标 -->
            <el-icon
                v-if="currentUser.role === 'ADMIN'"
                style="margin-left: 10px; cursor: pointer;"
                @click="togglePasswordVisibility(scope.row.id)">
              <component :is="passwordVisible[scope.row.id] ? 'View' : 'Hide'"/>
            </el-icon>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="role" label="权限">
  <template #default="scope">
    <el-tag 
      :type="getRoleType(scope.row.role)"
    >
      {{ getRoleName(scope.row.role) }}
    </el-tag>
  </template>
</el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
              size="small"
              @click="showEditUserDialog(scope.row)"
              :disabled="currentUser.role !== 'ADMIN'">
            编辑
          </el-button>
          <el-popconfirm
              title="确定要删除该用户吗？"
              @confirm="deleteUser(scope.row.id)"
              :disabled="currentUser.role !== 'ADMIN' || scope.row.id === currentUser.id">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
                  :disabled="currentUser.role !== 'ADMIN' || scope.row.id === currentUser.id">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :small="false"
          :disabled="false"
          :background="false"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="30%"
        @close="handleDialogClose">
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 添加用户时显示密码输入框 -->
        <template v-if="isAddUser">
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="userForm.password"
                type="password"
                autocomplete="off"
                show-password>
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
                v-model="userForm.confirmPassword"
                type="password"
                autocomplete="off"
                show-password>
            </el-input>
          </el-form-item>
        </template>

        <!-- 编辑用户时显示密码输入框（可选） -->
        <template v-else>
          <el-form-item label="新密码（留空则不修改）" prop="password">
            <el-input
                v-model="userForm.password"
                type="password"
                autocomplete="off"
                show-password
                placeholder="留空则不修改密码">
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword" v-if="userForm.password">
            <el-input
                v-model="userForm.confirmPassword"
                type="password"
                autocomplete="off"
                show-password
                placeholder="请再次输入新密码">
            </el-input>
          </el-form-item>
        </template>

        <el-form-item label="角色" prop="role" v-if="canEditRole">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="普通用户" value="USER"></el-option>
            <el-option label="中院用户" value="ZHONG"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref, onMounted, reactive, computed} from 'vue'
import request from '@/utils/request'
import {ElMessage, ElMessageBox} from 'element-plus'
import {View, Hide} from '@element-plus/icons-vue'

export default {
  name: 'UserManagement',
  components: {
    View,
    Hide
  },
  setup() {
    const users = ref([])
    const currentUser = ref({})
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isAddUser = ref(false)
    const searchUsername = ref('')
    const userFormRef = ref(null)

    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 密码可见性控制
    const passwordVisible = ref({})

    const userForm = reactive({
      id: null,
      username: '',
      password: '',
      confirmPassword: '',
      role: 'USER'
    })

    // 判断是否可以编辑角色（不能编辑自己和其他管理员的角色）
    const canEditRole = computed(() => {
      if (isAddUser.value) return true;
      // 编辑时，如果编辑的是自己或其他管理员，则不能编辑角色
      if (userForm.id === currentUser.value.id) return false;
      const targetUser = users.value.find(user => user.id === userForm.id);
      return !(targetUser && targetUser.role === 'ADMIN');
    });

    const userFormRules = {
      username: [
        {required: true, message: '请输入用户名', trigger: 'blur'}
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (isAddUser.value && !value) {
              callback(new Error('请输入密码'));
            } else {
              callback();
            }
          }
        },
        {min: 6, message: '密码长度至少6位', trigger: 'blur'}
      ],
      confirmPassword: [
        {
          required: true,
          message: '请确认密码',
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (isAddUser.value && !value) {
              callback(new Error('请确认密码'));
            } else if (userForm.password && value !== userForm.password) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          }
        }
      ],
      role: [
        {required: true, message: '请选择角色', trigger: 'change'}
      ]
    }

    // 获取当前用户信息
    const getCurrentUser = async () => {
      try {
        const response = await request.get('/user/info')
        if (response.code === 200) {
          currentUser.value = response.data
          await loadUsers()
        }
      } catch (error) {
        console.error('获取当前用户信息失败:', error)
      }
    }

    // 加载用户列表
    const loadUsers = async () => {
      try {
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }

        if (searchUsername.value) {
          params.username = searchUsername.value
        }

        const response = await request.get('/user/list', {params})
        if (response.code === 200) {
          users.value = response.records
          total.value = response.total
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载用户列表失败')
      }
    }

    // 搜索用户
    const searchUsers = () => {
      currentPage.value = 1
      loadUsers()
    }

    // 重置搜索
    const resetSearch = () => {
      searchUsername.value = ''
      currentPage.value = 1
      loadUsers()
    }

    // 处理分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      loadUsers()
    }

    // 处理当前页变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadUsers()
    }

    // 显示添加用户对话框
    const showAddUserDialog = () => {
      isAddUser.value = true
      dialogTitle.value = '添加用户'
      resetUserForm()
      dialogVisible.value = true
    }

    // 显示编辑用户对话框
    const showEditUserDialog = (user) => {
      isAddUser.value = false
      dialogTitle.value = '编辑用户'
      userForm.id = user.id
      userForm.username = user.username
      userForm.password = ''
      userForm.confirmPassword = ''
      userForm.role = user.role
      dialogVisible.value = true
    }

    // 重置表单
    const resetUserForm = () => {
      userForm.id = null
      userForm.username = ''
      userForm.password = ''
      userForm.confirmPassword = ''
      userForm.role = 'USER'
    }

    // 对话框关闭时重置表单
    const handleDialogClose = () => {
      resetUserForm()
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }

    // 切换密码可见性（仅管理员可用）
    const togglePasswordVisibility = (userId) => {
      if (currentUser.value.role === 'ADMIN') {
        passwordVisible.value[userId] = !passwordVisible.value[userId]
      }
    }

    // 保存用户（添加或编辑）
    const saveUser = async () => {
      userFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            let response
            if (isAddUser.value) {
              // 添加用户
              const formData = {
                username: userForm.username,
                password: userForm.password,
                role: userForm.role
              }
              response = await request.post('/user/add', formData)
            } else {
              // 编辑用户
              const formData = {
                id: userForm.id,
                username: userForm.username,
                role: userForm.role
              }

              // 如果输入了新密码，则添加到表单数据中
              if (userForm.password) {
                formData.password = userForm.password
              }

              response = await request.post('/user/update', formData)

              // 如果编辑的是当前登录用户，则提示重新登录
              if (userForm.id === currentUser.value.id) {
                await ElMessageBox.alert('用户信息已更新，请重新登录', '提示', {
                  confirmButtonText: '确定',
                  callback: () => {
                    // 退出登录
                    request.post('/user/logout').finally(() => {
                      window.location.reload()
                    })
                  }
                })
                return
              }
            }

            if (response.code === 200) {
              ElMessage.success(response.message)
              dialogVisible.value = false
              await loadUsers()
            } else {
              ElMessage.error(response.message)
            }
          } catch (error) {
            console.error('保存用户失败:', error)
            ElMessage.error('保存用户失败')
          }
        }
      })
    }

    // 删除用户
    const deleteUser = async (id) => {
      try {
        const response = await request.post('/user/delete', null, {
          params: {id: id}
        })
        if (response.code === 200) {
          ElMessage.success(response.message)
          // 如果删除的是当前页最后一条数据且不是第一页，则返回上一页
          if (users.value.length === 1 && currentPage.value > 1) {
            currentPage.value--
          }
          await loadUsers()
        } else {
          ElMessage.error(response.message)
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage.error('删除用户失败')
      }
    }

    onMounted(() => {
      getCurrentUser()
    })

    return {
      users,
      currentUser,
      dialogVisible,
      dialogTitle,
      isAddUser,
      userForm,
      userFormRules,
      searchUsername,
      currentPage,
      pageSize,
      total,
      passwordVisible,
      userFormRef,
      canEditRole,
      loadUsers,
      showAddUserDialog,
      showEditUserDialog,
      saveUser,
      deleteUser,
      searchUsers,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      togglePasswordVisibility,
      handleDialogClose
    }
  },
  methods: {
    // 获取角色显示名称
    getRoleName(role) {
      switch(role) {
        case 'ADMIN':
          return '管理员';
        case 'ZHONG':
          return '中院账户';
        case 'USER':
          return '普通用户';
        default:
          return '未知权限';
      }
    },
    // 获取角色标签类型
    getRoleType(role) {
      switch(role) {
        case 'ADMIN':
          return 'danger'; // 管理员用红色
        case 'ZHONG':
          return 'warning'; // 中院账户用橙色
        case 'USER':
          return 'success'; // 普通用户用绿色
        default:
          return 'info';
      }
    }
  }
}
</script>

<style scoped>
.user-management {
  width: 100%;
  padding: 10px;
}
</style>
